/**
 * author      : dormi330
 * date        : 2018/6/24
 * project     : mybatis
 * description : 领域行为: 创建订单
 */

package org.wzq.learn.domain.order;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.wzq.learn.order.InDtoAuditOrder;

import java.util.Date;

@Service
public class CommandAudit {

    private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

    @Autowired
    private OrderRepository orderRepository;

    /**
     * 新建订单
     *
     * @param tradeOrder      tradeOrder, 被审核的订单
     * @param inDtoAuditOrder 审核相关内容
     * @throws Exception
     */
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor = Exception.class)
    public boolean auditOne(TradeOrder tradeOrder, InDtoAuditOrder inDtoAuditOrder) throws Exception {

        if (null == tradeOrder) throw new Exception("order cannot be null");
        if (inDtoAuditOrder == null) throw new Exception("inDtoAuditOrder cannot be null");

        // 审批通过 -> 待付款
        // 拒绝 -> reject
        String fromStatus = tradeOrder.getStatus();
        if (!TradeOrder.STATUS_TO_BE_AUDITED.equals(tradeOrder.getStatus())) {
            throw new Exception("order cannot be auditOne, current status=" + tradeOrder.getStatus());
        }

        // now update status
        boolean isPass = inDtoAuditOrder.approve;
        String toStatus = isPass ? TradeOrder.STATUS_TO_BE_PAID : TradeOrder.STATUS_AUDIT_REJECTED;

        int count = orderRepository.updateTradeOrderStatus(
                tradeOrder.getTenantCode(),
                tradeOrder.getId(),
                fromStatus,

                toStatus,
                inDtoAuditOrder.rejectReason,
                new Date(),
                inDtoAuditOrder.auditorId
        );
        return count == 1;
    }
}
